<template>
  <Modal
    v-model="isShow"
    title="找回密码"
    :closable="false"
  >
    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
      <FormItem label="Email" prop="email">
        <Input v-model="formValidate.email"
          placeholder="Enter your email"
          style="width: 66%"
        />
        <SendEmailCodeButton
          :sendEmailCodeMethod="() => { return this.sendEmailCode('formValidate') }"
          buttonText="发送邮箱验证码"
          style="float: right"
        />
      </FormItem>
      <FormItem label="Code" prop="code">
        <Input v-model="formValidate.code" placeholder="Enter your email code" />
      </FormItem>
      <FormItem label="Password" prop="password">
        <Input v-model="formValidate.password" type="password" placeholder="Enter your password" />
      </FormItem>
      <FormItem label="Password" prop="password2">
        <Input v-model="formValidate.password2" type="password" placeholder="Repeat your password" />
      </FormItem>
    </Form>
    <div slot="footer">
      <Button type="primary" @click="handleSubmit('formValidate')">提交</Button>
      <Button @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
      <Button @click="setVisiable(false)" style="margin-left: 8px">关闭</Button>
    </div>
  </Modal>
</template>
<script>
import { emailExists, sendEmailCode as handleSendEmailCode, findPasswordByEmail } from '../api/auth'
import SendEmailCodeButton from '../views/SendEmailCodeButton'

export default {
  name: 'FindPassword',
  components: {
    SendEmailCodeButton
  },
  props: {
    isShow: {
      type: Boolean,
      required: true,
      default: false
    },
    setVisiable: {
      type: Function,
      required: true
    }
  },
  data () {
    return {
      formValidate: {
        code: '',
        email: '',
        password: '',
        password2: ''
      },
      ruleValidate: {
        code: [
          { required: true, message: 'The email code cannot be empty', trigger: 'blur' }
        ],
        email: [
          { required: true, message: 'email cannot be empty', trigger: 'blur' },
          { type: 'email', message: 'Incorrect email format', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              emailExists(value)
                .then(res => {
                  callback(new Error('该邮箱未绑定任何用户!'))
                })
                .catch(() => {
                  callback()
                })
            },
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: 'The password cannot be empty', trigger: 'blur' },
          { type: 'string', min: 5, max: 32, message: '密码必须由5-32位字母或数字组成', trigger: 'blur' }
        ],
        password2: [
          { required: true, message: 'The password cannot be empty', trigger: 'blur' },
          { type: 'string', min: 5, max: 32, message: '密码必须由5-32位字母或数字组成', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (this.validatePassword()) {
                callback()
              } else {
                callback(new Error('两次密码输入不一致'))
              }
            }
          }
        ]
      }
    }
  },
  methods: {
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          // console.log(this.formValidate)
          findPasswordByEmail(this.formValidate)
            .then(res => {
              this.$Notice.success({
                title: '密码修改成功!',
                desc: '本页面将于3秒后自动关闭!',
                duration: 5
              })
              setTimeout(() => {
                this.setVisiable(false)
              }, 3000)
            })
            .catch(err => {
              if (err.response) {
                this.$Notice.error({
                  title: '验证失败!',
                  desc: err.response.data.message,
                  duration: 5
                })
              }
            })
        }
      })
    },
    sendEmailCode (name) {
      this.$refs[name].validateField('email', (error) => {
        if (error) {
          return false
        } else {
          handleSendEmailCode(this.formValidate.email)
            .then(res => {
              this.formValidate = {
                ...this.formValidate,
                ...res.data
              }
              this.$Notice.success({
                title: '发送成功!',
                desc: '验证码已发送至您的邮箱，请尽快完成验证!',
                duration: 5
              })
            })
          return true
        }
      })
    },
    handleReset (name) {
      this.$refs[name].resetFields()
    },
    validatePassword () {
      return this.formValidate.password === this.formValidate.password2
    }
  }
}
</script>
